using System;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using E4RPManager.DataSets;
using E4RPTools;
using System.Windows.Forms;

namespace E4RPManager.Controls
{
    public partial class ClientXtraForm : XtraForm
    {
        private long _documentId;
        private Controller _controller;
        private ClienteDataSet _dataSet;

        #region Properties

        public long DocumentId
        {
            set { _documentId = value; }
        }

        public Controller Controller
        {
            set { _controller = value; }
        }

        #endregion

        public ClientXtraForm()
        {
            InitializeComponent();
            Load += ClientXtraForm_Load;
            gridView.InitNewRow += GridViewInitNewRow;
            okSimpleButton.Click += OkSimpleButtonClick;
        }

        #region Private Methods

        private void MergeData()
        {
            _dataSet = new ClienteDataSet();
            if (_documentId <= 0)
            {
                var document = _dataSet.Cliente.NewClienteRow();
                document.Id = _documentId;
                document.Nome = "";
                _dataSet.Cliente.AddClienteRow(document);
            }
            else
                _dataSet.Merge(_controller.GetClient(_documentId));
        }

        private void SetDataToControls()
        {
            nameTextEdit.Text = _dataSet.Cliente[0].Nome;
            addressTextEdit.Text = _dataSet.Cliente[0].IsMoradaNull() ? "" : _dataSet.Cliente[0].Morada;
            cityTextEdit.Text = _dataSet.Cliente[0].IsCidadeNull() ? "" : _dataSet.Cliente[0].Cidade;
            zipCodeTextEdit.Text = _dataSet.Cliente[0].IsCodigoPostalNull() ? "" : _dataSet.Cliente[0].CodigoPostal;
            fiscalNumberTextEdit.Text = _dataSet.Cliente[0].IsContribuinteNull() ? "" : _dataSet.Cliente[0].Contribuinte;
            phoneTextEdit.Text = _dataSet.Cliente[0].IsTelefoneNull() ? "" : _dataSet.Cliente[0].Telefone;
            mailTextEdit.Text = _dataSet.Cliente[0].IsEMailNull() ? "" : _dataSet.Cliente[0].EMail;
            remarksMemoEdit.Text = _dataSet.Cliente[0].IsObservacoesNull() ? "" : _dataSet.Cliente[0].Observacoes;
            webTextEdit.Text = _dataSet.Cliente[0].IsEnderecoWebNull() ? "" : _dataSet.Cliente[0].EnderecoWeb;
            faxTextEdit.Text = _dataSet.Cliente[0].IsFaxNull() ? "" : _dataSet.Cliente[0].Fax;
            gridControl.DataSource = null;
            gridControl.DataMember = "";
            gridControl.DataSource = _dataSet.ClienteProduto;
        }

        private void SetupProductLookupData()
        {
            produtoDataSet.Merge(_controller.GetProducts());
            productRepositoryItemLookUpEdit.Columns.Clear();
            productRepositoryItemLookUpEdit.Columns.AddRange(new[] {
                new LookUpColumnInfo("Id", "Id", 81, FormatType.None, "", false, HorzAlignment.Near),
                new LookUpColumnInfo("Nome", "Nome", 85, FormatType.None, "", true, HorzAlignment.Near)});
            productRepositoryItemLookUpEdit.DataSource = produtoDataSet.Produto;
            productRepositoryItemLookUpEdit.DisplayMember = produtoDataSet.Produto.NomeColumn.ColumnName;
            productRepositoryItemLookUpEdit.ValueMember = produtoDataSet.Produto.IdColumn.ColumnName;
        }

        private void SetupPartnerLookupData()
        {
            parceiroDataSet.Merge(_controller.GetPartners());
            partnerRepositoryItemLookUpEdit.Columns.Clear();
            partnerRepositoryItemLookUpEdit.Columns.AddRange(new[] {
                new LookUpColumnInfo("Id", "Id", 81, FormatType.None, "", false, HorzAlignment.Near),
                new LookUpColumnInfo("Nome", "Nome", 85, FormatType.None, "", true, HorzAlignment.Near)});
            partnerRepositoryItemLookUpEdit.DataSource = parceiroDataSet.Parceiro;
            partnerRepositoryItemLookUpEdit.DisplayMember = parceiroDataSet.Parceiro.NomeColumn.ColumnName;
            partnerRepositoryItemLookUpEdit.ValueMember = parceiroDataSet.Parceiro.IdColumn.ColumnName;
        }

        private void ClearControlErrors()
        {
            dxErrorProvider.SetError(nameTextEdit, "");
            dxErrorProvider.SetError(addressTextEdit, "");
            dxErrorProvider.SetError(cityTextEdit, "");
            dxErrorProvider.SetError(zipCodeTextEdit, "");
            dxErrorProvider.SetError(fiscalNumberTextEdit, "");
            dxErrorProvider.SetError(phoneTextEdit, "");
            dxErrorProvider.SetError(mailTextEdit, "");
            dxErrorProvider.SetError(remarksMemoEdit, "");
            dxErrorProvider.SetError(webTextEdit, "");
            dxErrorProvider.SetError(faxTextEdit, "");
            dxErrorProvider.SetError(gridControl, "");
        }

        private void GetDataFromControls()
        {
            _dataSet.Cliente[0].Nome = nameTextEdit.Text;
            _dataSet.Cliente[0].Morada = addressTextEdit.Text;
            _dataSet.Cliente[0].Cidade = cityTextEdit.Text;
            _dataSet.Cliente[0].CodigoPostal = zipCodeTextEdit.Text;
            _dataSet.Cliente[0].Contribuinte = fiscalNumberTextEdit.Text;
            _dataSet.Cliente[0].Telefone = phoneTextEdit.Text;
            _dataSet.Cliente[0].EMail = mailTextEdit.Text;
            _dataSet.Cliente[0].Observacoes = remarksMemoEdit.Text;
            _dataSet.Cliente[0].EnderecoWeb = webTextEdit.Text;
            _dataSet.Cliente[0].Fax = faxTextEdit.Text;
            gridView.CloseEditor();
            gridView.UpdateCurrentRow();
        }

        private Control GetControl(string reference)
        {
            switch (reference)
            {
                case "Nome":
                    return nameTextEdit;
                case "Morada":
                    return addressTextEdit;
                case "Cidade":
                    return cityTextEdit;
                case "CodigoPostal":
                    return zipCodeTextEdit;
                case "Contribuinte":
                    return fiscalNumberTextEdit;
                case "Telefone":
                    return phoneTextEdit;
                case "EMail":
                    return mailTextEdit;
                case "Observacoes":
                    return remarksMemoEdit;
                case "EnderecoWeb":
                    return webTextEdit;
                case "Fax":
                    return faxTextEdit;
                default:
                    return null;
            }
        }

        private void SetControlErrors(Result result)
        {
            foreach (var error in result.Errors)
                dxErrorProvider.SetError(GetControl(error.Reference), error.Message);
        }

        #endregion

        void ClientXtraForm_Load(object sender, EventArgs e)
        {
            MergeData();
            SetDataToControls();
            SetupProductLookupData();
            SetupPartnerLookupData(); 
        }

        void GridViewInitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            var document = (ClienteDataSet.ClienteProdutoRow)gridView.GetDataRow(e.RowHandle);
            document.IdCliente = _dataSet.Cliente[0].Id;
            document.Versao = 1;
            document.RegistadoEm = DateTime.Now;
        }

        void OkSimpleButtonClick(object sender, EventArgs e)
        {
            ClearControlErrors();
            GetDataFromControls();
            Result result = _controller.IsClientValid(_dataSet);
            if (result.Failed)
            {
                DialogResult = DialogResult.None;
                SetControlErrors(result);
            }
            else
                _controller.SaveClient(_dataSet);
        }

    }
}